// 学习进度API
import { NextRequest } from 'next/server';
import { ProgressDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取用户所有学习进度
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取用户进度
    const progress = await ProgressDB.getUserProgress(currentUser.userId);

    return ApiResponse.success({
      progress,
      total: progress.length,
    });
  } catch (error) {
    console.error('获取学习进度错误:', error);
    return ApiResponse.serverError('获取学习进度失败');
  }
}

// 更新学习进度
export async function POST(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 解析请求体
    const body = await request.json();
    const { topicId, topicName, isCorrect, timeSpent } = body;

    // 验证必填字段
    if (!topicId || !topicName || typeof isCorrect !== 'boolean' || !timeSpent) {
      return ApiResponse.error('缺少必填字段');
    }

    // 更新进度
    await ProgressDB.updateProgress(
      currentUser.userId,
      topicId,
      topicName,
      isCorrect,
      timeSpent
    );

    // 获取更新后的进度
    const updatedProgress = await ProgressDB.getTopicProgress(
      currentUser.userId,
      topicId
    );

    return ApiResponse.success(updatedProgress, '进度更新成功');
  } catch (error) {
    console.error('更新学习进度错误:', error);
    return ApiResponse.serverError('更新学习进度失败');
  }
}
